import React, { Component } from 'react'
import { Flex, WingBlank, WhiteSpace, Toast } from 'antd-mobile'
import { Link, withRouter } from 'react-router-dom'

//导入APi
import { API } from '../../utils/index.jsx'

import NavHeader from '../../components/NavHeader'

//导入withFormik(表单状态和提交)
//Form (代替原来表单)
//Field (代替原来input)
//ErrorMessage (代替原来错误信息)
import { withFormik, Form, Field, ErrorMessage } from 'formik'
//导入yup(表单验证功能模块)
import * as Yup from 'yup'

import styles from './index.module.css'

// 验证规则：
const REG_UNAME = /^[a-zA-Z_\d]{5,8}$/
const REG_PWD = /^[a-zA-Z_\d]{5,12}$/

class Login extends Component {
  render() {
    return (
      <div className={styles.root}>
        {/* 顶部导航 */}
        <NavHeader className={styles.navHeader} title={'账号登录'}></NavHeader>
        <WhiteSpace size="xl" />

        {/* 登录表单 */}
        <WingBlank>
          <Form>
            {/* 账号 */}
            <div className={styles.formItem}>
              <Field
                className={styles.input}
                type="username"
                name="username"
                placeholder="请输入账号"
              />
            </div>

            <ErrorMessage
              className={styles.error}
              component="div"
              name="username"
            />

            {/* 密码 */}
            <div className={styles.formItem}>
              <Field
                className={styles.input}
                type="password"
                name="password"
                placeholder="请输入密码"
              />
            </div>

            <ErrorMessage
              className={styles.error}
              component="div"
              name="password"
            />

            <div className={styles.formSubmit}>
              <button className={styles.submit} type="submit">
                登 录
              </button>
            </div>
          </Form>
          <Flex className={styles.backHome}>
            <Flex.Item>
              <Link to="/registe">还没有账号，去注册~</Link>
            </Flex.Item>
          </Flex>
        </WingBlank>
      </div>
    )
  }
}

// 注意：此处返回的是 高阶组件 包装后的组件
Login = withFormik({
  //提供状态
  mapPropsToValues: () => ({ username: '', password: '' }),
  //表单提交事件
  handleSubmit: async (values, { props }) => {
    const { username, password } = values
    const res = await API.post(`/user/login`, {
      username: username,
      password: password,
    })
    const { status, description, body } = res.data
    if (status !== 200) return Toast.info(description, 2, null, false)
    localStorage.setItem('hkzf_token', body.token)
    //直接登录
    if (!props.location.state) {
      //无法在this上找到props
      props.history.go(-1)
    } else {
      props.history.replace(props.location.state.from.pathname)
    }
  },
  //表单验证规则
  validationSchema: Yup.object().shape({
    username: Yup.string()
      .required('账号为必填项')
      .matches(REG_UNAME, '长度为5到8位，只能出现数字、字母、下划线'),
    password: Yup.string()
      .required('密码为必填项')
      .matches(REG_PWD, '长度为5到12位，只能出现数字、字母、下划线'),
  }),
})(Login)

export default withRouter(Login)
